import { localCache } from "./storageCache"
import { LoginKeyEnum } from "@/enums"

export const getImageUrl = (name: string) => new URL(`../assets/${name}`, import.meta.url).href

export function getUuid(): string {
  const temp_url = URL.createObjectURL(new Blob())
  const uuid = temp_url.toString()
  URL.revokeObjectURL(temp_url) //释放这个url
  return uuid.substring(uuid.lastIndexOf('/') + 1)
}

export function download(blob: Blob | null, filename: string = 'WFT.xlsx'): void {
  if(!blob) return
  const link = document.createElement('a')
  const URL = window.URL || window.webkitURL;
  const href = URL.createObjectURL(new Blob([blob]))
  link.href = href
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  // URL.revokeObjectURL(href) // 释放掉blob对象
}

export function getObjType(obj: any) {
  let map: { [key: string]: any } = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }
  if (obj instanceof Element) {
    return 'element'
  }
  return map[Object.prototype.toString.call(obj)]
}

export function debounce(fn: Function, wait: number) {
  let timer: number | null = null
  return function() {
    if(timer) {
      clearTimeout(timer)
      timer = null
    }
    timer = setTimeout(fn, wait)
  }
}

export const animationsClass = (classNames: string[]) => {
  if(classNames?.length) {
    return `animate__animated animate__${classNames[0]}`
  }
  return ''
}

export function clearLoginInfo() {
  localCache.removeCache(LoginKeyEnum.SET_TOKEN_KEY)
}